package cn.wolfcode.luowowo.comment.service.impl;


import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentRepository strategyCommentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    public void save(StrategyComment strategyComment) {
        strategyComment.setCreateTime(new Date());
        strategyCommentRepository.save(strategyComment);
    }

    public Page query(StrategyCommentQuery qo) {
        Query query = new Query();
        //Criteria criteria = new Criteria("detailId").is(qo.getDetailId());
        //Criteria.where("detailId") =new Criteria(detailId)
        //注意这里的page当前页是从0开始的
        Pageable pageable= PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");
        //查询总条数
        long count = mongoTemplate.count(query, StrategyComment.class);
        query.with(pageable);
        //查询当前显示数据集合
        if(qo.getDetailId()!=-1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        List<StrategyComment> strategyComments = mongoTemplate.find(query, StrategyComment.class);
        return new PageImpl(strategyComments,pageable,count);
    }

    public void commentThumbUp(String commentId, Long userId) {
        //根据传过来评论人的id,拿到评论用户相关的信息 放在mongodb中
        Optional<StrategyComment> comment = strategyCommentRepository.findById(commentId);
        StrategyComment strategyComment = comment.get();
        if(strategyComment==null){
            throw new LogicException("参数异常");
        }
        //1.判断当前请求是点赞还是取消
        //1.1判断当前请求用户是否在点在集合中
        List<Long> list = strategyComment.getThumbuplist();
        //1.2如果在那么是取消点赞,否则是点赞
        if(list.contains(userId)){
            //2.2取消点赞,点赞数-1,删除点赞集合中的用户
            strategyComment.setThumbupnum(strategyComment.getThumbupnum()-1);
            list.remove(userId);
        }else{
            strategyComment.setThumbupnum(strategyComment.getThumbupnum()+1);
            list.add(userId);
            //2.1放入当前点赞集合中,点赞数+1
        }
        strategyCommentRepository.save(strategyComment);
    }
}
